package com.kushe.dao;

import com.kushe.entity.User;
import com.kushe.util.core.DataAccess;
import com.kushe.util.tools.SecUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;

import java.util.List;

/**
 * Created by WhiteBlue on 15/3/30.
 */
public class UserDao extends DataAccess<User> {

    public User get(int id) {
        return getDao().fetch(User.class, id);
    }

    public User getByCookies(String id, String pw_md5) {
        return getDao().fetch(User.class, Cnd.where("id", "=", id).and("password", "=", pw_md5));
    }

    public User getByPw(String email, String password) {
        return getDao().fetch(User.class, Cnd.where("email", "=", email).and("password", "=", SecUtils.encoderByMd5With32Bit(password)));
    }

    public User addUser(String email, String name, String password) {
        Dao dao = getDao();
        if (dao.fetch(User.class, Cnd.where("name", "=", name)) == null) {
            User user = new User();
            user.setEmail(email);
            user.setName(name);
            user.setImg("default.jpg");
            user.setPassword(SecUtils.encoderByMd5With32Bit(password));
            dao.insert(user);
            return user;
        } else
            return null;
    }

    public boolean checkName(String name) {
        if (getDao().count(User.class, Cnd.where("name", "=", name)) == 0)
            return true;
        else
            return false;
    }

    public boolean checkEmail(String email) {
        if (getDao().count(User.class, Cnd.where("email", "=", email)) == 0)
            return true;
        else
            return false;
    }

    public User editInfo(User user, String feeling, String name, int sex) {
        user.setFeeling(feeling);
        user.setSex(sex);
        if (checkName(name))
            user.setName(name);
        getDao().update(user);
        return user;
    }

    public User editAddress(User user, String address, String phone, String postNumber, String trueName) {
        user.setAddress(address);
        user.setPhone(phone);
        user.setPostNumber(postNumber);
        user.setTrueName(trueName);
        getDao().update(user);
        return user;
    }


    public List<User> getByName(String name) {
        return getDao().query(User.class, Cnd.where("name", "like", "%" + name + "%"));
    }

    public List<User> getForIndex() {
        return getDao().query(User.class, Cnd.limit().limit(5).desc("count"));
    }

    public void changeHead(User user, String imgUrl) {
        try {
            user.setImg(imgUrl);
            getDao().update(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
